package com.tanhua.admin.service;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.tanhua.admin.mapper.AnalysisMapper;
import com.tanhua.admin.mapper.LogMapper;
import com.tanhua.model.db.Analysis;
import com.tanhua.model.vo.AnalysisSummaryVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;

@Service
@Slf4j
public class AnalysisService {

    @Autowired
    private LogMapper logMapper;

    @Autowired
    private AnalysisMapper analysisMapper;

    public void analysis() {
        String today = DateUtil.today();
        String yesToday = DateUtil.yesterday().toDateStr();

        //1 统计Log表的数据
        //1.1 统计今日新增用户数
        Integer numRegistered = logMapper.countNumRegisteredToday(today);
        //1.2活跃用户数
        Integer numActive = logMapper.countNumActiveByDate(today);
        //1.3登陆次数
        Integer numLogin = logMapper.countNumLoginByDate(today);
        //1.4次日留存用户数
        Integer numRetention1d = logMapper.countNumRetention1d(today, yesToday);
        log.debug("*******numRegistered**{}***********numActive****{}*************numLogin**{}***********numRetention1d****{}******", numRegistered, numActive, numLogin, numRetention1d);

        //2 根据今天时间查询Analysis表记录是否存在
        Analysis analysis = analysisMapper.findByRecordDate(today);
        Date nowDate = new Date();

        //3 如果今天记录存在，更新Analysis数据
        if (analysis != null) {
            analysis.setNumRegistered(numRegistered);//统计今日新增用户数
            analysis.setNumActive(numActive);///活跃用户数
            analysis.setNumLogin(numLogin);//登陆次数
            analysis.setNumRetention1d(numRetention1d);///次日留存用户数
            analysis.setUpdated(nowDate);//更新时间
            analysisMapper.updateById(analysis);
            log.debug("******************更新数据了**************************");
        }else {
            //4 如果今日记录不存在，直接保存Analysis数据
            analysis = new Analysis();
            analysis.setRecordDate(DateUtil.parseDate(today));
            analysis.setNumRegistered(numRegistered);//统计今日新增用户数
            analysis.setNumActive(numActive);///活跃用户数
            analysis.setNumLogin(numLogin);//登陆次数
            analysis.setNumRetention1d(numRetention1d);///次日留存用户数
            analysis.setCreated(nowDate);//创建时间
            analysis.setUpdated(nowDate);//更新时间
            analysisMapper.insert(analysis);
            log.debug("******************新增数据了**************************");
        }
    }

    /**
     * 概要统计信息-累计注册用户数 过去7天活跃用户数 ......
     */
    public AnalysisSummaryVo summary() {
        String today = DateUtil.today();
        String yesterday = DateUtil.yesterday().toDateStr();
        DateTime todayDateTime = DateUtil.parseDate(today);
        DateTime yesterdayDateTime = DateUtil.parseDate(yesterday);


        AnalysisSummaryVo vo = new AnalysisSummaryVo();
        vo.setCumulativeUsers(analysisMapper.totalUser());//累计用户数
        vo.setActivePassMonth(analysisMapper.countActive(DateUtil.offsetDay(todayDateTime,-30)));//过去30天活跃用户数
        vo.setActivePassWeek(analysisMapper.countActive(DateUtil.offsetDay(todayDateTime,-7)));//过去7天活跃用户

        Long todayNewUsers = analysisMapper.countNewUsers(today);
        Long yesterdayNewUsers = analysisMapper.countNewUsers(yesterday);
        vo.setNewUsersToday(todayNewUsers);//今日新增用户数量
        vo.setNewUsersTodayRate(computeRate(todayNewUsers,yesterdayNewUsers));//今日新增用户涨跌率

        Long todayLoginTimes = analysisMapper.countLoginTimes(today);
        Long yesterdayLoginTimes = analysisMapper.countLoginTimes(yesterday);
        vo.setLoginTimesToday(todayLoginTimes);//今日登录次数
        vo.setLoginTimesTodayRate(computeRate(todayLoginTimes,yesterdayLoginTimes));//今日登录次数涨跌率

        Long todayActiveUsers = analysisMapper.countActiveUsers(today);
        Long yesterdayActiveUsers = analysisMapper.countActiveUsers(yesterday);
        vo.setActiveUsersToday(todayActiveUsers);//今日活跃用户数量
        vo.setActiveUsersTodayRate(computeRate(todayActiveUsers,yesterdayActiveUsers));//今日活跃用户涨跌率
        log.debug("************************首页统计分析查询***********************");
        return vo;
    }



    /**
     * 传入当前时间 上一次时间
     * @param current
     * @param last
     * @return
     */
    private static BigDecimal computeRate(Long current, Long last) {
        BigDecimal result;
        if (last == 0) {
            // 当上一期计数为零时，此时环比增长为倍数增长
            result = new BigDecimal((current - last) * 100);
        } else {
            result = BigDecimal.valueOf((current - last) * 100).divide(BigDecimal.valueOf(last), 2, BigDecimal.ROUND_HALF_DOWN);
        }
        return result;
    }
}


